<template>
    <div>
        <!-- 共用头部组件 -->
        <common-header
            headerTitle="在线客服"
            :hasBack="true"
            :hasHome="true"
        ></common-header>
        <!-- 共用头部组件 -->

        <!-- 共用页面滚动组件 -->
        <common-scroll
            :scrollStyle="scrollStyle"
            :isPulldown="true"
            :data="chatList"
            :scrollToEndFlag="scrollToEndFlag"
            @pulldown="loadMoreMessage"
            @isToBottom="isToBottom"
        >
            <!-- 聊天内容组件 -->
            <div class="chat-box">
                <div
                    class="message-item"
                    v-for="(item,index) of chatList"
                    :key="index"
                >
                    <div class="time-box">{{item.messageTime}}</div>
                    <div
                        class="user-message-box"
                        v-if="item.chatType == 1"
                    >
                        <div
                            class="message-box"
                            v-html="item.textMessage"
                            v-if="item.textMessage"
                        ></div>
                        <div
                            class="message-box"
                            v-if="item.pictureMessage"
                        >
                            <img
                                class="picture"
                                :src="item.pictureMessage"
                                @click="lookPicture(item.pictureMessage)"
                            />
                        </div>
                        <div class="header-pic"><img :src="item.userHeader"></div>
                    </div>
                    <div
                        class="kefu-message-box"
                        v-if="item.chatType == 0"
                    >
                        <div class="header-pic"><img :src="item.userHeader"></div>
                        <div
                            class="message-box"
                            v-html="item.textMessage"
                            v-if="item.textMessage"
                        ></div>
                        <div
                            class="message-box"
                            v-if="item.pictureMessage"
                        >
                            <img
                                class="picture"
                                :src="item.pictureMessage"
                                @click="lookPicture(item.pictureMessage)"
                            />
                        </div>
                    </div>
                </div>
            </div>
            <!-- 聊天内容组件 -->

        </common-scroll>
        <!-- 共用页面滚动组件 -->

        <!-- 聊天输入组件 -->
        <div class="chat-input-box">
            <div class="image">
                <input
                    id="sendImage"
                    type="file"
                    @change="sendPictureMessage"
                />
            </div>
            <!-- <div class="emoji"></div> -->
            <div class="text">
                <input
                    id="textInput"
                    type="text"
                />
            </div>
            <div
                id="sendMessage"
                @click="sendTextMessage"
            >发送</div>
        </div>
        <!-- 聊天输入组件 -->

        <!-- 查看图片组件 -->
        <div
            class="picture-box"
            v-show="pictureImg"
            @click="pictureImg = ''"
        >
            <img
                class="picture-item"
                :src="pictureImg"
            />
        </div>
        <!-- 查看图片组件 -->
    </div>
</template>

<script>
import CommonHeader from '@/components/Header'
import CommonScroll from '@/components/Scroll'
export default {
    name: 'ServiceOnline',
    components: {
        CommonHeader,
        CommonScroll
    },
    data () {
        return {
            scrollStyle: {
                top: "1.11rem",
                left: "0",
                right: "0",
                bottom: "1.46rem"
            },
            kefuName: 'xiantehui',
            chatList: [],
            historyChatList: [],
            currentPage: 1,
            lastTime: 0,
            pictureImg: '',
            scrollToEndFlag: true,
            userName: 'xiantehui123',
            userPassword: '123456'
        }
    },
    mounted () {
        this.autoLogin()
        if (localStorage.getItem(this.userName + '_history')) {
            this.historyChatList = JSON.parse(localStorage.getItem(this.userName + '_history'))
            if (this.historyChatList) {
                this.historyChatList.reverse().forEach((item, i) => {
                    if (i < 10) {
                        this.chatList.unshift(item)
                    }
                })
            }
        }
    },
    methods: {
        autoLogin () {
            const that = this
            this.conn = new WebIM.connection({
                https: WebIM.config.https,
                url: WebIM.config.xmppURL,
                isAutoLogin: WebIM.config.isAutoLogin,
                isMultiLoginSessions: WebIM.config.isMultiLoginSessions
            })
            this.options = {
                apiUrl: WebIM.config.apiURL,
                user: this.userName,
                pwd: this.userPassword,
                appKey: WebIM.config.appkey
            }
            this.conn.listen({
                onOpened: function (message) {          //连接成功回调
                    console.log('链接已成功建立')
                },
                onClosed: function (message) {
                    console.log('登录超时')             //连接关闭回调
                },
                onTextMessage: function (message) {
                    that.getTextMessage(message.data)  //收到文本消息
                },
                onEmojiMessage: function (message) {
                    // let text = ''
                    // let data = message.data;
                    // for (let i = 0, l = data.length; i < l; i++) {
                    //     if (data[i].type == 'txt') {
                    //         text += data[i].data
                    //     } else if (data[i].type == 'emoji') {
                    //         text += '<img class="emoji" src="' + data[i].data + '" />'
                    //     }
                    // }
                    // that.getEmojiMessage(text)
                },   //收到表情消息
                onPictureMessage: function (message) {
                    that.getPictureMessage(message.url)             //收到图片消息
                },
                onCmdMessage: function (message) { },     //收到命令消息
                onAudioMessage: function (message) { },   //收到音频消息
                onLocationMessage: function (message) { },//收到位置消息
                onFileMessage: function (message) { },    //收到文件消息
                onVideoMessage: function (message) { },   //收到视频消息
                onPresence: function (message) { },       //收到联系人订阅请求、处理群组、聊天室被踢解散等消息
                onRoster: function (message) { },         //处理好友申请
                onInviteMessage: function (message) { },  //处理群组邀请
                onOnline: function () { },                  //本机网络连接成功
                onOffline: function () { },                 //本机网络掉线
                onError: function (message) { },          //失败回调
                onBlacklistUpdate: function (list) { }
            })
            this.conn.open(this.options)
        },
        getTextMessage (data) {
            let time = this.getNowTime()
            this.chatList.push(
                {
                    chatType: 0,
                    messageTime: time,
                    userHeader: require('@/assets/images/serviceOnline/kefu-icon.png'),
                    textMessage: data,
                    pictureMessage: null
                }
            )
            this.saveMessage()
            this.scrollToBottom()
        },
        sendTextMessage () {
            let time = this.getNowTime()
            let textMessage = document.getElementById('textInput').value
            let id = this.conn.getUniqueId();                 // 生成本地消息id
            let msg = new WebIM.message('txt', id);      // 创建文本消息
            msg.set({
                msg: textMessage,                  // 消息内容
                to: this.kefuName,                          // 接收消息对象（用户id）
                roomType: false,
                success: function (id, serverMsgId) {
                }
            });
            msg.body.chatType = 'singleChat';
            if (textMessage) {
                this.conn.send(msg.body);
                document.getElementById('textInput').value = ''
                this.chatList.push(
                    {
                        chatType: 1,
                        messageTime: time,
                        userHeader: require('@/assets/images/serviceOnline/header-icon.png'),
                        textMessage: textMessage,
                        pictureMessage: null
                    }
                )
                this.saveMessage()
                this.scrollToBottom()
            }
        },
        getPictureMessage (data) {
            let time = this.getNowTime()
            this.chatList.push(
                {
                    chatType: 0,
                    messageTime: time,
                    userHeader: require('@/assets/images/serviceOnline/kefu-icon.png'),
                    textMessage: null,
                    pictureMessage: data
                }
            )
            this.saveMessage()
            this.scrollToBottom()
        },
        sendPictureMessage () {
            let that = this
            let time = this.getNowTime()
            let picture
            let id = this.conn.getUniqueId();                   // 生成本地消息id
            let msg = new WebIM.message('img', id);        // 创建图片消息
            let input = document.getElementById('sendImage');  // 选择图片的input
            let file = WebIM.utils.getFileUrl(input);      // 将图片转化为二进制文件
            let allowType = {
                'jpg': true,
                'gif': true,
                'png': true,
                'bmp': true
            };
            if (file.filetype.toLowerCase() in allowType) {
                let option = {
                    apiUrl: WebIM.config.apiURL,
                    file: file,
                    to: this.kefuName,                       // 接收消息对象
                    roomType: false,
                    chatType: 'singleChat',
                    onFileUploadError: function () {      // 消息上传失败
                        console.log('onFileUploadError');
                    },
                    onFileUploadComplete: function (res) {   // 消息上传成功
                        console.log('onFileUploadComplete');
                        picture = res.uri + '/' + res.entities[0].uuid
                        that.chatList.push(
                            {
                                chatType: 1,
                                messageTime: time,
                                userHeader: require('@/assets/images/serviceOnline/header-icon.png'),
                                textMessage: null,
                                pictureMessage: picture
                            }
                        )
                        that.saveMessage()
                        that.scrollToBottom()
                    },
                    success: function () {                // 消息发送成功
                        console.log('Success');
                    },
                    flashUpload: WebIM.flashUpload
                };
                msg.set(option);
                this.conn.send(msg.body);
            }
        },
        getEmojiMessage (data) {
            let time = this.getNowTime()
            this.chatList.push(
                {
                    chatType: 0,
                    messageTime: time,
                    userHeader: require('@/assets/images/serviceOnline/kefu-icon.png'),
                    textMessage: data,
                    pictureMessage: null
                }
            )
        },
        getNowTime () {
            let date = new Date()
            let y = date.getFullYear()
            let m = date.getMonth() + 1
            m = m < 10 ? ('0' + m) : m
            let d = date.getDate()
            d = d < 10 ? ('0' + d) : d
            let h = date.getHours()
            h = h < 10 ? ('0' + h) : h
            let minute = date.getMinutes()
            let second = date.getSeconds()
            minute = minute < 10 ? ('0' + minute) : minute
            second = second < 10 ? ('0' + second) : second
            if (Math.ceil((date.getTime() - this.lastTime) / 1000 / 60) > 5) {
                this.lastTime = date.getTime()
                return y + '-' + m + '-' + d + ' ' + h + ':' + minute + ':' + second
            }
            else {
                return ''
            }
        },
        saveMessage () {
            localStorage.setItem(this.userName + '_history', JSON.stringify(this.chatList))
        },
        scrollToBottom () {
            this.scrollToEndFlag = true
        },
        isToBottom () {
            this.scrollToEndFlag = false
        },
        lookPicture (data) {
            this.pictureImg = data
        },
        loadMoreMessage () {
            if (this.currentPage < Math.floor(this.historyChatList.length / 10) + 1) {
                this.historyChatList.forEach((item, i) => {
                    if (i >= 10 * this.currentPage && i < 10 * this.currentPage + 10) {
                        this.chatList.unshift(item)
                    }
                })
                this.currentPage++
            }
        }
    }
}
</script>

<style lang="stylus" scoped>
.chat-box
    padding 0.53rem 0.32rem
    .message-item
        margin-bottom 0.46rem
        .time-box
            font-size 0.34rem
            color #999
            text-align center
        .user-message-box
            display flex
            justify-content flex-end
            margin-top 0.27rem
            .message-box
                max-width 70%
                position relative
                font-size 0.42rem
                color #333
                padding 0.21rem 0.26rem
                line-height 1.5
                background #fff
                border 1px solid #d3d3d4
                border-radius 5px
                word-break break-all
                word-wrap break-word
                .picture
                    max-width 100%
                    height 1.85rem
            .header-pic
                margin-left 0.4rem
                width 1.06rem
                height 1.06rem
                overflow hidden
                img
                    width 100%
                    height 100%
            .message-box:after
                position absolute
                top 0.32rem
                right -0.16rem
                display block
                width 0.16rem
                height 0.34rem
                content ''
                background-image url('../../assets/images/serviceOnline/user-trangle.png')
                background-repeat no-repeat
                background-size 100% 100%
        .kefu-message-box
            display flex
            justify-content flex-start
            margin-top 0.27rem
            .message-box
                max-width 70%
                position relative
                font-size 0.42rem
                color #333
                padding 0.21rem 0.26rem
                line-height 1.5
                background #ffe4b5
                border 1px solid #d3d3d4
                border-radius 5px
                word-break break-all
                word-wrap break-word
                .picture
                    max-width 100%
                    height 1.85rem
            .header-pic
                margin-right 0.4rem
                width 1.06rem
                height 1.06rem
                overflow hidden
                img
                    width 100%
                    height 100%
            .message-box:after
                position absolute
                top 0.32rem
                left -0.16rem
                display block
                width 0.16rem
                height 0.34rem
                content ''
                background-image url('../../assets/images/serviceOnline/kefu-trangle.png')
                background-repeat no-repeat
                background-size 100% 100%
.chat-input-box
    position absolute
    bottom 0
    left 0
    right 0
    height 1.46rem
    padding 0 0.26rem
    background #fff
    border-top 1px solid #e5e5e5
    box-sizing border-box
    display flex
    align-items center
    .image
        width 0.72rem
        height 0.72rem
        background-image url('../../assets/images/serviceOnline/add-icon.png')
        background-repeat no-repeat
        background-size 100% 100%
        overflow hidden
        #sendImage
            display block
            width 100%
            height 100%
            opacity 0
    .emoji
        width 0.72rem
        height 0.72rem
        background-image url('../../assets/images/serviceOnline/expression-icon.png')
        background-repeat no-repeat
        background-size 100% 100%
        margin-left 0.26rem
    .text
        display flex
        align-items center
        flex 1
        height 0.96rem
        margin 0 0.26rem
        border 1px solid #d3d3d4
        border-radius 3px
        padding 0 0.26rem
        #textInput
            flex 1
            font-size 0.42rem
            color #333
            border none
            outline none
    #sendMessage
        width 1.33rem
        line-height 0.96rem
        height 0.96rem
        background #d7463c
        font-size 0.4rem
        color #fff
        text-align center
        border-radius 3px
.picture-box
    position fixed
    top 0
    left 0
    right 0
    bottom 0
    background-color rgba(0, 0, 0, 0.9)
    display flex
    align-items center
    justify-content center
    overflow hidden
    .picture-item
        max-width 100%
        max-height 100%
</style>
